import requests
import json
from django.conf import settings
from .models import AIConfig, ChatSession


class DeepSeekService:
    """DeepSeek AI服务类"""
    
    def __init__(self):
        self.config = None
    
    def get_active_config(self):
        """获取活跃的AI配置"""
        try:
            return AIConfig.objects.filter(is_active=True).first()
        except AIConfig.DoesNotExist:
            # 如果没有配置，创建默认配置
            return AIConfig.objects.create(
                name="默认DeepSeek配置",
                api_key="your-deepseek-api-key",
                api_url="https://api.deepseek.com/v1/chat/completions",
                model_name="deepseek-chat"
            )
    
    def get_or_create_session(self, session_id):
        """获取或创建聊天会话"""
        session, created = ChatSession.objects.get_or_create(
            session_id=session_id,
            defaults={'context': []}
        )
        return session
    
    def add_to_context(self, session, role, content):
        """添加消息到上下文"""
        if not session.context:
            session.context = []
        
        session.context.append({
            "role": role,
            "content": content
        })
        
        # 保持上下文长度不超过10条对话
        if len(session.context) > 20:
            session.context = session.context[-20:]
        
        session.save()
    
    def chat_with_deepseek(self, message, session_id):
        """与DeepSeek进行对话"""
        if not self.config:
            self.config = self.get_active_config()
        
        if not self.config or not self.config.api_key:
            return "错误：未配置DeepSeek API密钥"
        
        try:
            # 获取会话
            session = self.get_or_create_session(session_id)
            
            # 添加用户消息到上下文
            self.add_to_context(session, "user", message)
            
            # 准备系统提示
            system_prompt = {
                "role": "system",
                "content": "你是一个专业的智能客服助手，请用中文回复用户的问题。你应该友好、耐心、专业地帮助用户解决问题。"
            }
            
            # 构建消息列表
            messages = [system_prompt] + session.context
            
            # 调用DeepSeek API
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.config.api_key}"
            }
            
            payload = {
                "model": self.config.model_name,
                "messages": messages,
                "max_tokens": self.config.max_tokens,
                "temperature": self.config.temperature,
                "stream": False
            }
            
            response = requests.post(
                self.config.api_url,
                headers=headers,
                json=payload,
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                ai_response = result['choices'][0]['message']['content']
                
                # 添加AI回复到上下文
                self.add_to_context(session, "assistant", ai_response)
                
                return ai_response
            else:
                error_msg = f"API调用失败: {response.status_code} - {response.text}"
                return f"抱歉，我现在无法回答您的问题。请稍后再试。({error_msg})"
                
        except requests.exceptions.Timeout:
            return "抱歉，响应超时了，请稍后再试。"
        except requests.exceptions.RequestException as e:
            return f"抱歉，网络连接出现问题：{str(e)}"
        except Exception as e:
            return f"抱歉，出现了未知错误：{str(e)}"
    
    def clear_session(self, session_id):
        """清除会话上下文"""
        try:
            session = ChatSession.objects.get(session_id=session_id)
            session.context = []
            session.save()
            return True
        except ChatSession.DoesNotExist:
            return False


# 全局服务实例
deepseek_service = DeepSeekService()